﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace LibSnesDotNet.Input
{
	public class InputAggregator : InputProvider
	{
		List<InputDriver> _driversList;
		ReadOnlyCollection<InputDriver> _drivers;

		public ReadOnlyCollection<InputDriver> Drivers { get { return _drivers; } }

		public InputAggregator()
		{
			_driversList = new List<InputDriver>();
			_drivers = _driversList.AsReadOnly();
		}

		public void AddDriver(InputDriver driver)
		{
			if (_driversList.Contains(driver))
			{
				throw new ArgumentException(driver.Name + " is already present.");
			}

			driver.InputReceived += InputHandler;
			_driversList.Add(driver);
		}

		public void RemoveDriver(InputDriver driver)
		{
			try
			{
				driver.InputReceived -= InputHandler;
				_driversList.Remove(driver);
			}
			catch
			{
				throw new ArgumentException(driver.Name + " driver is not present.");
			}
		}

		public void DisposeAllDrivers()
		{
			foreach (InputDriver driver in _driversList)
			{
				driver.InputReceived -= InputHandler;
				driver.Dispose();
			}

			_driversList.Clear();
		}

		public Input GetInput(string driverName, string deviceName, string inputName)
		{
			foreach (InputDriver driver in _driversList)
			{
				if (driver.Name == driverName)
				{
					return driver.GetInput(deviceName, inputName);
				}
			}

			throw new ArgumentException(driverName + " driver is not present.");
		}

		void InputHandler(object sender, InputReceivedEventArgs e)
		{
			OnInputReceived(e);
		}

	}
}
